﻿using GodSharp.Sockets;
using System;
using System.Data;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace TcpServerDemo
{
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
        }

        private void Main_Load(object sender, EventArgs e)
        {
            StartSocket();
        }

        void AppendText(string message)
        {
            this.Invoke(new Action(() =>
            {
                tbMsg.AppendText($"{DateTime.Now:yyyy-MM-dd HH:mm:ss}:{message}\r\n");
            }));
        }

        #region GodSharpSocket
        ITcpServer SocketServer;
        /// <summary>
        /// 用来存储最新一个连接，当只有一个客户端时方便使用
        /// </summary>
        ITcpConnection SocketConnection;
        void StartSocket()
        {
            try
            {
                SocketServer = new TcpServer(5005, "10.0.0.1")
                {
                    OnConnected = (c) =>
                    {
                        AppendText($"{c.RemoteEndPoint} connected.");
                        SocketConnection = c.NetConnection;
                    },
                    OnReceived = (c) =>
                    {
                        AppendText($"Received from {c.RemoteEndPoint}:");
                        AppendText(string.Join(" ", c.Buffers.Select(x => x.ToString("X2")).ToArray()));

                        c.NetConnection.Send(c.Buffers);
                        c.NetConnection.Send(new byte[] { 0x00, 0x00, 0x0B, 0x30, 0x30, 0x30, 0x30, 0x30, 0x41, 0x43, 0x4B });
                    },
                    OnDisconnected = (c) =>
                    {
                        AppendText($"{c.RemoteEndPoint} disconnected.");
                    },
                    OnStarted = (c) =>
                    {
                        AppendText($"{c.LocalEndPoint} started.");
                    },
                    OnStopped = (c) =>
                    {
                        AppendText($"{c.LocalEndPoint} stopped.");
                    },
                    OnException = (c) =>
                    {
                        AppendText($"{c.RemoteEndPoint} exception:{c.Exception.StackTrace}.");
                    },
                    OnServerException = (c) =>
                    {
                        AppendText($"{c.LocalEndPoint} exception:{c.Exception.StackTrace}.");
                    }
                };
                SocketServer.UseKeepAlive();
                SocketServer.Start();
                AppendText("GodSharp.Socket.TcpServer Started!");

                CheckClient();
            }
            catch (Exception ex)
            {
                AppendText(ex.ToString());
            }

            void CheckClient()
            {
                //客户端断网后大概20秒才会发送失败从而执行OnDisconnected方法，服务器断开网络会立刻检测到
                try
                {
                    Task.Run(() =>
                    {
                        while (true)
                        {
                            foreach (var item in SocketServer.Connections)
                            {
                                //item.Value.Send(new byte[0]);//发送0字节，客户端断网的话，服务端仍能一直发送，会导致捕获不到客户端断开
                                item.Value.Send(new byte[] { 0x00 });//对应ASCII 空字符
                            }
                            Thread.Sleep(2000);
                        }
                    });
                }
                catch (Exception ex)
                {
                    AppendText(ex.Message);
                    CheckClient();
                }
            }
        }
        #endregion
    }
}
